/**
 * 
 */
package com.lastproject.web.bean;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import com.lastproject.dto.UserDTO;
import com.lastproject.ejb.dao.UserDAORemote;

/**
 * @author Alexandra
 *
 */

@ManagedBean
@SessionScoped
public class LoginBean {
	
	@ManagedProperty(value = "#{userDTO}")
	private UserDTO userDTO;
	
	private String logUsername;
	private String logPassword;

	@EJB
	UserDAORemote userDAO;
	
	private String invalid;
	
	public LoginBean () {
		
	}
	
	public LoginBean(UserDTO userDTO) {
		this.userDTO = userDTO;
	}

	public UserDTO getUserDTO() {
		return userDTO;
	}

	public void setUserDTO(UserDTO userDTO) {
		this.userDTO = userDTO;
	}

	public String getLogUsername() {
		return logUsername;
	}

	public void setLogUsername(String logUsername) {
		this.logUsername = logUsername;
	}

	public String getLogPassword() {
		return logPassword;
	}

	public void setLogPassword(String logPassword) {
		this.logPassword = logPassword;
	}
	
	public String loginMethod() {
		UserDTO userToLogDTO = userDAO.userLogin(logUsername, logPassword);
		FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("userDTO", userToLogDTO);
		
		invalid="";
		
		if(userToLogDTO != null) {
			System.out.println("return home");
			return "home";
		} else {
			invalid="Invalid Credentials";
//			FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
			return "login?faces-redirect=true";
		}
	}
	
	public String logoutMethod() {		
		FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
		
		System.out.println("After logout, on session: " + 
				FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("userDTO"));
		return "login?faces-redirect=true";
	}

	public String getInvalid() {
		return invalid;
	}

	public void setInvalid(String invalid) {
		this.invalid = invalid;
	}
	
	
}
